package vn.student.message;

import java.util.ArrayList;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class DownloadServiceManager extends Service
{
    ArrayList<String> arrayList = new ArrayList<String>();
    //id cua tin can lay'
    private static final String ID_KEY="id";
    private static final String COMPLETE="complete";
    @Override
    public IBinder onBind(Intent intent)
    {
	return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
	String id = intent.getStringExtra(ID_KEY);
	if (id.equalsIgnoreCase(COMPLETE))
	{
	    if (arrayList.size() == 0)
	    {
		stopSelf();
	    }
	    else
	    {
		startDownloadService();
	    }
	}
	else
	{
	    arrayList.add(id);
	    if (!isDownloadServiceRunning(Constants.CLASS_DOWNLOADSERVICE))
	    {
		startDownloadService();
	    }
	}
	
	return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onDestroy()
    {
	super.onDestroy();
    }
    
    private void startDownloadService()
    {
	Intent i = new Intent(Constants.CLASS_DOWNLOADSERVICE);
	i.putExtra(ID_KEY, arrayList.get(0));
	arrayList.remove(0);
	startService(i);
    }
    
    public boolean isDownloadServiceRunning(String className)
    {
	ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
	for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
	{
	    if (className.equals(service.service.getClassName()))
	    {
		return true;
	    }
	}
	return false;
    }
}
